<template>
  <view>
    <up-form :model="form" :rules="rules" ref="uFormRef">
      <block v-for="(item,index) in formJson" :key="index">
        <up-form-item :label="item.label" label-width="fit-content" :required="item.required"
          :labelPosition="item.labelPosition||'left'" :borderBottom="item.border" @click="changeSelect(item)"
          :prop="item.required?item.key:''" v-if="item.type != 'houseItem'">
          <up-input :maxlength="item.maxlength||-1" v-model="form[item.key]" border="none" input-align="right"
            :placeholder="item.placeholder" v-if="item.type == 'text'" :disabled="is_disabled">
            <template #suffix>
              <view>{{item.suffix || ''}}</view>
              <view v-if="item.radio" class="u-flex-y-center u-m-l-36">
                <view class="u-flex-y-center" @click.stop="changeRadio(1)">
                  <image src="@/static/images/01_18mj.png" class="radio-icon" v-if="form.sex == 1"></image>
                  <image src="@/static/images/01_18efd.png" class="radio-icon" v-else></image>
                  <text>先生</text>
                </view>
                <view class="u-flex-y-center u-m-l-36" @click.stop="changeRadio(2)">
                  <image src="@/static/images/01_18mj.png" class="radio-icon" v-if="form.sex == 2"></image>
                  <image src="@/static/images/01_18efd.png" class="radio-icon" v-else></image>
                  <text>女士</text>
                </view>
              </view>
            </template>
          </up-input>
          <up-input v-model="form[item.key_text]" input-align="right" v-if="item.type == 'datetime'" border="none"
            :placeholder="item.placeholder" readonly :disabled="is_disabled">
            <template #suffix>
              <up-icon name="arrow-right" size="16" color="#000"></up-icon>
            </template>
          </up-input>
          <view v-if="item.type=='radio'" class="u-flex-y-center u-flex-end u-m-l-36">
            <view class="u-flex-y-center" @click.stop="changeRadio(1)">
              <image src="@/static/images/01_18mj.png" class="radio-icon" v-if="form.sex == 1"></image>
              <image src="@/static/images/01_18efd.png" class="radio-icon" v-else></image>
              <text>先生</text>
            </view>
            <view class="u-flex-y-center u-m-l-36" @click.stop="changeRadio(2)">
              <image src="@/static/images/01_18mj.png" class="radio-icon" v-if="form.sex == 2"></image>
              <image src="@/static/images/01_18efd.png" class="radio-icon" v-else></image>
              <text>女士</text>
            </view>
          </view>
          <up-input v-model="form[item.key_text]" input-align="right" v-if="item.type == 'select'" border="none"
            :placeholder="item.placeholder" readonly :disabled="is_disabled">
            <template #suffix>
              <up-icon name="arrow-right" size="16" color="#000"></up-icon>
            </template>
          </up-input>
          <up-input v-model="form[item.key_text]" input-align="right" v-if="item.type == 'region'" border="none"
            :placeholder="item.placeholder" readonly :disabled="is_disabled">
            <template #suffix>
              <up-icon name="arrow-right" size="16" color="#000"></up-icon>
            </template>
          </up-input>
          <view v-if="item.type == 'upload'">
            <up-upload width="180rpx" height="180rpx" :fileList="fileList" multiple max-count="9" @afterRead="afterRead"
              @delete="deletePic" :disabled="is_disabled">
              <image src="@/static/images/01_18hjm.png" mode="widthFix" style="width: 180rpx;height: 180rpx;"></image>
            </up-upload>
            <view class="remark">
              {{item.remark}}
            </view>
          </view>
          <up-upload v-else-if="item.type == 'uploadVideo'" width="180rpx" height="180rpx" multiple
            :fileList="videoList" max-count="1" @afterRead="afterChange($event,'videoList')" accept="video"
            @delete="deletePic($event,'videoList')">
            <image src="@/static/images/01_18hjm.png" mode="widthFix" style="width: 180rpx;height: 180rpx;"></image>
          </up-upload>
          <up-textarea v-model="form[item.key]" v-if="item.type == 'textarea'" border="none"
            :placeholder="item.placeholder" :disabled="is_disabled"></up-textarea>
          <view v-if="item.type == 'switch'" class="u-flex u-flex-end">
            <u-image :src="form[item.key] == 1? '/static/images/kaig.png':'/static/images/kai.png'" width="116rpx"
              height="64rpx" @click="changeSwitch(item)"></u-image>
          </view>
          <u-text v-if="item.type == 'total_money'" color="#999" :text="`${form.hb_price * form.hb_number || 0}元`"
            align="right"></u-text>
        </up-form-item>
        <up-form-item :label="item.label" label-width="fit-content" :required="item.required"
          :labelPosition="item.labelPosition||'left'" :borderBottom="item.border" v-else
          @click="$u.route('/pages/index/newsList/changeHouse')">
          <up-input input-align="right" border="none" :placeholder="item.placeholder" readonly :disabled="is_disabled">
            <template #suffix>
              <up-icon name="arrow-right" size="16" color="#000"></up-icon>
            </template>
          </up-input>
        </up-form-item>
        <view v-if="item.type == 'houseItem'">
          <house-item customStyle="margin-top:-20rpx" page="/" v-if="data.houseInfo.id" :item="data.houseInfo"
            :imageWidth="234" imageHeight="192">
            <template #right>
              <view class="u-flex-between u-flex-column u-flex-fill">
                <view class="house-name u-flex-y-center u-flex-between">
                  <view>{{data.houseInfo.title}}</view>
                  <u-image src="/static/images/01_34ghj.png" @click="handleDel" width="34rpx" height="34rpx"
                    :fade="false"></u-image>
                </view>
                <view class="house-desc">“{{data.houseInfo.description}}”</view>
                <view class="house-info">“{{data.houseInfo.space}}㎡ | {{data.houseInfo.house_type_text}} | 简装”</view>
                <view class="house-price u-flex-y-center u-flex-between">
                  <text>市场价：{{data.houseInfo.market_price}}万</text>
                  <text>优惠价：{{data.houseInfo.price}}万</text>
                </view>
              </view>
            </template>
          </house-item>
        </view>
      </block>
    </up-form>
    <slot name="action" :form="form">
      <view class="action-bar">
        <view class="action-text" v-if="remarkShow">这里是注意事项</view>
        <up-button type="warning" shape="circle" color="#F87610" v-if="!is_disabled"
          @click="handleSubmit">确认提交</up-button>
        <up-button type="warning" shape="circle" color="#F87610" v-else @click="_sell_delete">下架房源</up-button>
      </view>
    </slot>
  </view>
  <up-picker :show="data.show" :columns="data.actions" keyName="name" closeOnClickOverlay @close="handleCancel"
    @cancel="handleCancel" @confirm="handleConfirm"></up-picker>
  <region-item :regionShow="data.regionShow" @update:regionShow="data.regionShow = $event"
    @confirmRegion="confirmRegion"> </region-item>
  <up-datetime-picker @confirm="dateConfirm" @cancel="dateCancel" :hasInput="false" :show="data.dateShow"
    v-model="dateNumber" mode="datetime"></up-datetime-picker>
</template>

<script setup>
  import { sell_delete, upload } from '../../config/api';
  import { _upload } from '../../util/util';
  import houseItem from '../house-item/house-item.vue';
  import { timeFormat } from 'uview-plus'
  import {
    computed,
    nextTick,
    onBeforeUnmount,
    onMounted,
    ref,
    watch,
    watchEffect
  } from 'vue';
  const emit = defineEmits(['handleConfirm', 'hadnleSubmit'])
  let props = defineProps({
    formJson: {
      type: Array,
      default: () => []
    },
    remarkShow: {
      type: Boolean,
      default: false
    },
    modal: {
      type: Object,
      default: () => {}
    },
    is_disabled: {
      type: Boolean,
      default: false
    }
  })
  const dateNumber = Number(new Date())
  let fileList = ref([])
  let videoList = ref([])
  let uFormRef = ref(null)
  let rules = computed(() => {
    let rulesObj = {}
    props.formJson.forEach(item => {
      if (item.required && item.key) {
        rulesObj[item.type == 'select' ? item.key_text : item.key] = {
          required: true,
          trigger: ['change', 'blur'],
          message: item.placeholder
        }
      }
    })
    return rulesObj
  })
  let data = ref({
    show: false,
    actions: [],
    key: '',
    key_text: '',
    regionShow: false,
    dateShow: false,
    houseInfo: {}
  })
  let form = ref({
    sex: 1
  })
  uni.$on('formEvent', item => {
    console.log(item)
    form.value.house_id = item.id
    data.value.houseInfo = item
  })
  onBeforeUnmount(() => {
    uni.$off('formEvent')
  })
  watch(() => props.modal, (newVal, oldVal) => {
    if (!uni.$u.test.isEmpty(props.modal)) {
      form.value = { ...form.value, ...props.modal }
      console.log(form.value)
    }
  }, { deep: true })
  const _sell_delete = () => {
    sell_delete({ id: props.id }).the(res => {
      uni.$u.toast(res.msg)
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    })
  }
  const handleDel = () => {
    form.value.house_id = ''
    data.value.houseInfo = {}
  }
  const changeSwitch = (item) => {
    form.value[item.key] = form.value[item.key] == 1 ? 0 : 1
  }
  const dateConfirm = (item) => {
    form.value[data.value.key] = timeFormat(item.value, 'yyyy-mm-dd MM:ss')
    form.value[data.value.key_text] = timeFormat(item.value, 'yyyy-mm-dd MM:ss')
    dateCancel()
  }
  const dateCancel = () => {
    data.value.dateShow = false
  }
  // 选择省市区
  const confirmRegion = (row) => {
    form.value = { ...form.value, ...row }
    let index = props.formJson.findIndex(item => item.type == 'region')
    form.value[props.formJson[index].key_text] =
      `${form.value.province_text}-${form.value.city_text}-${form.value.district_text}`
  }
  // 上传图片和视频
  const afterChange = async (event) => {
    let list = [].concat(event.file)
    let index = videoList.value.length
    list.forEach((item) => {
      videoList.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });
    for (let i = 0; i < list.length; i++) {
      const result = await _upload(list[i].url)
      let item = videoList.value[index];
      videoList.value.splice(index, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      index++
    }
  }
  // 删除图片
  const deleteVideo = (event, key) => {
    videoList.value.splice(event.index, 1)
  }

  // 上传图片
  const afterRead = async (event) => {
    let list = [].concat(event.file)
    let index = fileList.value.length
    list.forEach((item) => {
      fileList.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });
    for (let i = 0; i < list.length; i++) {
      const result = await _upload(list[i].url)
      let item = fileList.value[index];
      fileList.value.splice(index, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      index++
    }
  }
  // 删除图片
  const deletePic = (event) => {
    fileList.value.splice(event.index, 1)
  }
  // 提交
  const handleSubmit = () => {
    if (fileList.value.length) {
      let arr = []
      fileList.value.forEach(item => arr.push(item.url))
      form.value.images = arr.join(',')
    }
    if (videoList.value.length) {
      let arr = []
      videoList.value.forEach(item => arr.push(item.url))
      form.value.video = arr.join(',')
    }
    if (uni.$u.test.isEmpty(rules.value)) {
      emit('handleSubmit', form.value)
      return
    }
    uFormRef.value.validate().then(valid => {
      if (valid) {
        emit('handleSubmit', form.value)
      }
    })
  }
  // 下拉选择框打开
  const changeSelect = (item) => {
    if ((item.type != 'select' && item.type != 'region' && item.type != 'datetime') || props.is_disabled) return
    data.value.actions = [item.selectList]
    data.value.key = item.key
    data.value.key_text = item.key_text ?? ''
    if (item.type == 'region') data.value.regionShow = true
    else if (item.type == 'datetime') data.value.dateShow = true
    else data.value.show = true
  }
  // 选择性别
  const changeRadio = (value, item) => {
    form.value.sex = value
  }
  // 下拉选择
  const handleConfirm = (row) => {
    data.value.show = false
    form.value[data.value.key] = row.value[0]?.id || row.value[0]?.value
    form.value[data.value.key_text] = row.value[0].name
    emit('handleConfirm', { result: row.value, key: data.value.key })
  }
  // 关闭
  const handleCancel = () => {
    data.value.show = false
  }
</script>

<style scoped lang="scss">
  .radio-icon {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
  }

  .remark {
    font-size: 26rpx;
    font-weight: 500;
    color: #8f8f8f;
  }

  .action-bar {
    padding: 30rpx;
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 16rpx solid #f8f8f8;
    z-index: 9;

    .action-text {
      color: #F3440E;
      font-size: 24rpx;
      margin-bottom: 20rpx;
    }
  }

  .house-name {
    font-size: 26rpx;
    color: #333;
    font-weight: 800;
  }

  .house-info {
    font-size: 24rpx;
    font-weight: 500;
    color: #666;
  }

  .house-desc {
    font-size: 22rpx;
    color: #E47117;
  }

  .house-price {
    color: #DF0F0F;
    font-weight: 800;
    font-size: 24rpx;
  }
</style>